// shell2.hxx


#ifndef _BLOGS_SHELL2
#define _BLOGS_SHELL2


#include <cmath>
#include <type_traits>

#include "array.hxx"
#include "comparable.hxx"
#include "stack.hxx"
#include "std_out.hxx"


namespace blogs
{


class Shell2
{

  private:

    template
    <
        class _T,
        class = typename std::enable_if<std::is_base_of<Comparable<_T>, _T>::value>::type
    >
    static
    bool
    __less__(_T const& v, _T const& w)
    {
        return v.compare_to(w) < 0;
    }


  public:

    template
    <
        class _T,
        class = typename std::enable_if<std::is_base_of<Comparable<_T>, _T>::value>::type
    >
    static
    void
    sort(Array<_T> & a)
    {
        int N = a.size();
        int h1, h2, k = 0;
        Stack<int> hs;
        do {
            h1 = int(9 * std::pow(4, k) - 9 * std::pow(2, k) + 1);
            if (h1 < N) hs.push(h1);
            h2 = int(std::pow(4, k+2) - 3 * std::pow(2, k+2) + 1);
            if (h2 < N) hs.push(h2);
            ++k;
        } while (h1 < N || h2 < N);
        int h;
        while (!hs.is_empty()) {
            h = hs.pop();
            for (int i = h; i < N; ++i) {
                _T t = a[i];
                int j;
                for (j = i; j >= h && __less__(t, a[j-h]); j -= h)
                    a[j] = a[j-h];
                a[j] = t;
            }
        }
    }


    template
    <
        class _T,
        class = typename std::enable_if<std::is_base_of<Comparable<_T>, _T>::value>::type
    >
    static
    bool
    is_sorted(Array<_T> const& a)
    {
        int N = a.size();
        for (int i = 1; i < N; ++i)
            if (__less__(a[i], a[i-1])) return false;
        return true;
    }

};


} // end of namespace blogs


#endif

